package com.ycode.bang.anbang.baseui;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.ycode.bang.anbang.MyApp;
import com.ycode.bang.anbang.R;
import com.ycode.bang.anbang.utils.MyLog;
import com.ycode.bang.anbang.utils.MyStringRequest;

import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by ken on 2016/3/24.
 * Description : Activity的基类
 */
public abstract class BaseActivity<T> extends FragmentActivity {
    private final String TAG = this.getClass().getSimpleName();
    //    protected TreeMap<String, String> headers = new TreeMap<>();
    protected LayoutInflater inflater;
    protected LinearLayout rootLayout;
    protected RelativeLayout headLayout;
    protected ImageView backImageView, doImageViewRight, headImageView;
    protected TextView titleTextView, doTextViewRight;
    protected Context baseContext;
    protected Bundle bundle;

    protected ProgressDialog progressDialog;
    protected String progressString;
    WeakReference<Activity> softBitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        MyLog.e(TAG, "come to " + TAG);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        super.onCreate(savedInstanceState);
        softBitmap = new WeakReference<Activity>(this);
        MyApp.instance.addActivity(softBitmap);
        setContentView(R.layout.base);

        inflater = getLayoutInflater();
        rootLayout = (LinearLayout) findViewById(R.id.base_linearlayout_all);
        headLayout = (RelativeLayout) findViewById(R.id.head_relativelayout_all);
        backImageView = (ImageView) findViewById(R.id.head_imageView_back);
        titleTextView = (TextView) findViewById(R.id.head_textView_title);
        doTextViewRight = (TextView) findViewById(R.id.head_textView_do);
        doImageViewRight = (ImageView) findViewById(R.id.head_imageView_do);
        headImageView = (ImageView) findViewById(R.id.head_imageView);


        backImageView.setOnClickListener(baseOnClickListener);
        doImageViewRight.setOnClickListener(baseOnClickListener);
        doTextViewRight.setOnClickListener(baseOnClickListener);
        bundle = new Bundle();
        baseContext = this;

        progressString = getResources().getString(R.string.waiting);


    }

    public View addOurView(int viewId) {
        View view = null;
        // LayoutInflater inflater = getLayoutInflater();
        view = inflater.inflate(viewId, null);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout
                .LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        rootLayout.addView(view, params);
        return view;
    }

    public View addOurView(View view) {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout
                .LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        rootLayout.addView(view, params);
        return view;
    }

    public void jumpIntoOtherUI(Class<?> cls) {
        Intent intent = new Intent(baseContext, cls);
        if (cls.toString().equals("LoginActivity.class")) {
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        }
        intent.putExtras(bundle);
        baseContext.startActivity(intent);
        // overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
    }

    View.OnClickListener baseOnClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (v == backImageView) {
                finishActivity();
            } else if (v == doImageViewRight || v == doTextViewRight) {
                doOnClickRight(v);
            }
        }
    };

    public void doOnClickRight(View v) {

    }

    public void doOnClickLeft(View v) {

    }


    public void finishActivity() {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ((MyApp) getApplication()).removeActivity(softBitmap);
    }


    @Override
    protected void onStop() {
        super.onStop();
        //关闭请求
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public void onBackPressed() {
        int count = getFragmentManager().getBackStackEntryCount();

        if (count == 0) {
            super.onBackPressed();
            //additional code
        } else {
            getFragmentManager().popBackStack();
        }
    }

    protected void toast(CharSequence hint) {
        Toast.makeText(this, hint, Toast.LENGTH_SHORT).show();
    }

    protected void toast(CharSequence hint, int time) {
        Toast.makeText(this, hint, time).show();
    }


    protected void getHttpGetRequest(String url, final Class<T> cls, final int flag,
                                     String... str) {
        final String uri = getUrl(url, str);
        StringRequest stringRequest = new StringRequest(uri, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (progressDialog != null) {
                    progressDialog.dismiss();
                }
                com.orhanobut.logger.Logger.d(uri, response.toString());
                Gson gson = new Gson();
                T object = (T) gson.fromJson(response.toString(), cls);// 得到对象
                Message message = new Message();
                message.obj = object;
                message.arg1 = flag;
                handler.sendMessage(message);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (progressDialog != null) {
                    progressDialog.dismiss();
                }
                if (error.getMessage() != null) {
                    Log.e("VolleyError", error.getMessage(), error);
                }
            }
        });

        //请求加上Tag,用于取消请求
        stringRequest.setTag(flag);
        MyApp.instance.mRequestQueue.add(stringRequest);
    }

    protected void getHttpPostRequest(final String url, final Class<T> cls, final int flag,
                                      String...
                                              strings) {

        Map<String, String> param = new HashMap<String, String>();
        for (int i = 0; i < strings.length; i += 2) {
            param.put(strings[i], strings[i + 1]);
        }
        MyStringRequest jr = new MyStringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String response) {
                        if (progressDialog != null) {
                            progressDialog.dismiss();
                        }
                        // TODO Auto-generated method stub
                        com.orhanobut.logger.Logger.d(url, response.toString());
                        Gson gson = new Gson();
                        T object = (T) gson.fromJson(response.toString(), cls);// 得到对象
                        Message message = new Message();
                        message.obj = object;
                        message.arg1 = flag;
                        handler.sendMessage(message);
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                // TODO Auto-generated method stub
                if (progressDialog != null) {
                    progressDialog.dismiss();
                }
                if (error.getMessage() != null) {
                    Log.e("VolleyError", error.getMessage(), error);
                }
            }
        }, param);
        //请求加上Tag,用于取消请求
        jr.setTag(flag);
        MyApp.instance.mRequestQueue.add(jr);
    }

    protected void getHttpPutRequest(String url, final Class<T> cls, final int flag, String...
            strings) {

        final String uri = getUrl(url, strings);
        Logger.d(uri);
        StringRequest stringRequest = new StringRequest(Request.Method.PUT, uri, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (progressDialog != null) {
                    progressDialog.dismiss();
                }
                com.orhanobut.logger.Logger.d(uri, response.toString());
                Gson gson = new Gson();
                T object = (T) gson.fromJson(response.toString(), cls);// 得到对象
                Message message = new Message();
                message.obj = object;
                message.arg1 = flag;
                handler.sendMessage(message);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (progressDialog != null) {
                    progressDialog.dismiss();
                }
                if (error.getMessage() != null) {
                    Log.e("VolleyError", error.getMessage(), error);
                }
            }
        });

        //请求加上Tag,用于取消请求
        stringRequest.setTag(flag);
        MyApp.instance.mRequestQueue.add(stringRequest);
    }

    protected abstract void getSuccessRequest(T response, int flag);

//    protected abstract void getimageRequest(Bitmap bitmap, boolean bool);

    android.os.Handler handler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            getSuccessRequest((T) msg.obj, msg.arg1);
            switch (msg.what) {
                case 999:
                    MyApp.instance.loginOut();
                    break;
            }
        }
    };


    public String getUrl(String url, String... objects) {

        if (objects != null) {
            url = url + "?";
            for (int i = 0; i < objects.length; i = i + 2) {
                String tempString = null;
                try {
                    tempString = URLEncoder.encode(objects[i + 1], "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                url = url + objects[i] + "=" + tempString;
                if (i != objects.length - 2) {
                    url = url + "&";
                }
            }
        }
        return url;
    }

    protected void loginout_550(int error) {

        if (error == 500) {
            handler.sendEmptyMessage(999);
        }
    }
}
